package com.xiaoq.users.repository;

import com.xiaoq.users.entity.UserPhoneEntity;
import com.xiaoq.vo.PagingVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenjh on 2018/3/27.
 */
@Repository
public class UserPhoneRepository {

    @Autowired
    private Datastore datastore;

    private static final Logger LOG = LoggerFactory.getLogger(UserPhoneRepository.class);

    public boolean save(UserPhoneEntity userPhoneEntity){
        if(userPhoneEntity == null || StringUtils.isBlank(userPhoneEntity.getId())){
            return false;
        }

        if(StringUtils.isNotBlank(userPhoneEntity.getUserId())){
            Query<UserPhoneEntity> query = datastore.createQuery(UserPhoneEntity.class).filter("userId = ", userPhoneEntity.getUserId());
            if(query.count() > 0){
                return true;
            }
        }
        datastore.save(userPhoneEntity);
        return true;
    }


    public boolean update(UserPhoneEntity userPhoneEntity){
        if(userPhoneEntity == null || StringUtils.isBlank(userPhoneEntity.getId())){
            return false;
        }
        Query<UserPhoneEntity> query = datastore.createQuery(UserPhoneEntity.class)
                .filter("_id", userPhoneEntity.getId());
        UpdateOperations<UserPhoneEntity> userPhoneUpdate = datastore.createUpdateOperations(UserPhoneEntity.class);

        userPhoneUpdate.set("updatedAt", System.currentTimeMillis());
        if(StringUtils.isNotBlank(userPhoneEntity.getAreaCode())){
            userPhoneUpdate.set("areaCode", userPhoneEntity.getAreaCode());
        }
        if(StringUtils.isNotBlank(userPhoneEntity.getCity())){
            userPhoneUpdate.set("city", userPhoneEntity.getCity());
        }
        if(StringUtils.isNotBlank(userPhoneEntity.getCorp())){
            userPhoneUpdate.set("corp", userPhoneEntity.getCorp());
        }
        if(StringUtils.isNotBlank(userPhoneEntity.getMobile())){
            userPhoneUpdate.set("mobile", userPhoneEntity.getMobile());
        }
        if(StringUtils.isNotBlank(userPhoneEntity.getProvince())){
            userPhoneUpdate.set("province", userPhoneEntity.getProvince());
        }
        if(StringUtils.isNotBlank(userPhoneEntity.getPostCode())){
            userPhoneUpdate.set("postCode", userPhoneEntity.getPostCode());
        }
        if(userPhoneEntity.getPhoneValid() != null){
            userPhoneUpdate.set("phoneValid", userPhoneEntity.getPhoneValid());
        }
        if(StringUtils.isNotBlank(userPhoneEntity.getUserId())){
            userPhoneUpdate.set("userId", userPhoneEntity.getUserId());
        }
        datastore.update(query, userPhoneUpdate);
        return true;
    }

    /**
     * @param province 省份(可为null)
     * @param city 城市(可为null)
     * @param areaCode 区域码(可为null)
     * @param pagingVo 分页参数
     * @return
     */
    public List<UserPhoneEntity> getUserPhoneList(String province, String city, String areaCode, PagingVo pagingVo) {
        Query<UserPhoneEntity> query = datastore.createQuery(UserPhoneEntity.class)
                .filter("phoneValid", true);

        if(StringUtils.isNotBlank(city)){
            query.filter("city", city);
        }
        if(StringUtils.isNotBlank(province)){
            query.filter("province", province);
        }
        if(StringUtils.isNotBlank(areaCode)){
            query.filter("areaCode", areaCode);
        }
        if(pagingVo != null){
            query.offset(pagingVo.getPageOffset()).limit(pagingVo.getPs());
        }
        return query.asList();
    }

    /**
     * @param province 省份(可为null)
     * @param city 城市(可为null)
     * @param areaCode 区域码(可为null)
     * @return
     */
    public long getUserPhoneListCount(String province, String city, String areaCode) {
        Query<UserPhoneEntity> query = datastore.createQuery(UserPhoneEntity.class)
                .filter("phoneValid", true);

        if(StringUtils.isNotBlank(city)){
            query.filter("city", city);
        }
        if(StringUtils.isNotBlank(province)){
            query.filter("province", province);
        }
        if(StringUtils.isNotBlank(areaCode)){
            query.filter("areaCode", areaCode);
        }
        return query.count();
    }

    /**
     *  根据电话号码或者userId 获取用户的归属地信息
     *  id 和 userId 不能全为null
     * @param userId userId
     * @param mobile 电话号码
     * @return
     */
    public UserPhoneEntity getUserPhoneByIdOrMobile(String userId, String mobile){
        Query<UserPhoneEntity> query = datastore.createQuery(UserPhoneEntity.class)
                .filter("phoneValid", true);
        if(StringUtils.isAllBlank(userId, mobile)){
            return null;
        }
        if(StringUtils.isNotBlank(userId)){
            query.filter("userId", userId);
        }
        if(StringUtils.isNotBlank(mobile)){
            query.filter("mobile", mobile);
        }
        query.order("- createdAt");
        return query.get();
    }

    /**
     *  定时任务用
     * @param limit
     * @return
     */
    public List<UserPhoneEntity> getUserPhoneList4ScheduleNeedUpdpate(int limit){
        Query<UserPhoneEntity> query = datastore.createQuery(UserPhoneEntity.class)
                .field("phoneValid").doesNotExist()
                .limit(limit)
                .order("createdAt");
        return query.asList();
    }

    /**
     * 定时任务用
     * @return
     */
    public long getUserPhoneListCount4ScheduleNeedUpdpate(){
        Query<UserPhoneEntity> query = datastore.createQuery(UserPhoneEntity.class)
                .field("phoneValid").doesNotExist();
        return query.count();
    }


    public List<UserPhoneEntity> getUserPhoneList(List<String> userIdList) {
        if(CollectionUtils.isEmpty(userIdList)){
            return new ArrayList<>();
        }
        Query<UserPhoneEntity> query = datastore.createQuery(UserPhoneEntity.class)
                .filter("phoneValid", true)
                .filter("userId in", userIdList);
        return query.asList();
    }

    public List<UserPhoneEntity> getUserPhoneListByAreaCodeList(List<String> areaCodeList) {
        if(CollectionUtils.isEmpty(areaCodeList)){
            return new ArrayList<>();
        }
        Query<UserPhoneEntity> query = datastore.createQuery(UserPhoneEntity.class)
                .filter("phoneValid", true)
                .filter("areaCode in", areaCodeList);
        return query.asList();
    }


}
